import { defineStore } from 'pinia'
import { setCookieItem, getCookieItem, removeCookieItem } from '@/utils/storage'
import { resetRouter } from '@/router/index'
import { useTagsViewStore } from '@/store/tagsView'
import { logOut } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getCookieItem('token'),
    userInfo: getCookieItem('userInfo')
  }),
  actions: {
    setToken({ token }) {
      this.token = token
      setCookieItem('token', token)
    },
    setUserInfo({ userInfo }) {
      this.userInfo = {
        ...userInfo,
        // ✅ 强制将 roles 转为数组格式，避免后续报错
        name: userInfo.userName, // 兼容后端返回的 userName 和 nameq
        roles: Array.isArray(userInfo.roles) ? userInfo.roles : [userInfo.roles]
      }
      setCookieItem('userInfo', this.userInfo)
    },
    // utils/cookie.ts
    getCookieItem(key) {
      const cookieStr = document.cookie
      const match = cookieStr.match(new RegExp('(^| )' + key + '=([^;]*)(;|$)'))
      return match ? JSON.parse(decodeURIComponent(match[2])) : null
    },

    async logout() {
      const tagsViewStore = useTagsViewStore()
      //向后端发起退出登录状态请求，销毁token
      logOut()
      return new Promise((resolve) => {
        this.token = ''
        this.userInfo = null
        removeCookieItem('token')
        removeCookieItem('userInfo')
        resetRouter()
        tagsViewStore.delAllViews()
        resolve()
      })
    },
    resetToken() {
      return new Promise((resolve) => {
        this.token = ''
        this.userInfo = null
        removeCookieItem('token')
        removeCookieItem('userInfo')
        resolve()
      })
    }
  }
})
